import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/ball_pulse_footer.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

/*
 * 三方控件 ：   https://github.com/xuelongqy/flutter_easyrefresh
 */
class YRefreshWidget extends StatelessWidget {
  YRefreshWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("上拉加载,下拉刷新"),
      ),
      body: YRefreshFulWidget(),
    );
  }
}

class YRefreshFulWidget extends StatefulWidget {
  @override
  _YRefreshWidgetState createState() => _YRefreshWidgetState();
}

class _YRefreshWidgetState extends State<YRefreshFulWidget> {
  //获取到的字典集合
  List<String> _words = [];

  EasyRefreshController _controller;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(seconds: 2)).then((val) {
      _words.addAll(_getRefreshData());
      setState(() {});
    });
    _controller = EasyRefreshController();
  }

  @override
  Widget build(BuildContext context) {
    //  _controller.finishRefresh(success: true);
    //  _controller.finishLoad(success: true, noMore: true);
    return Container(
      child: EasyRefresh(
        controller: _controller,
        enableControlFinishLoad: true,
        enableControlFinishRefresh: true,
        child: ListView.separated(
            itemBuilder: (BuildContext context, int index) {
              return ListTile(title: Text(_words[index]));
            },
            separatorBuilder: (context, index) => Divider(height: .0),
            itemCount: _words.length),
        onRefresh: () async {
          _controller.resetLoadState();
          _words.clear();
          await Future.delayed(Duration(seconds: 2)).then((val) {
            _words.addAll(_getRefreshData());
           // _controller.resetRefreshState();
            _controller.finishRefresh();
            setState(() {});
          });
        },
        onLoad: () async {
          _controller.resetRefreshState();
          if (_words.length < 100) {
            await Future.delayed(Duration(seconds: 2)).then((val) {
              _words.addAll(_getRefreshData());
             // _controller.resetLoadState();
              _controller.finishLoad();
              setState(() {});
            });
          } else {
            _controller.finishLoad(success: true, noMore: true);
          }
        },
      ),
    );
  }

  /*获取数据*/
  List<String> _getRefreshData() {
    return generateWordPairs().take(20).map((e) => e.asPascalCase).toList();
  }
}
